import java.io.PrintStream;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.mozilla.interfaces.nsIDOMNamedNodeMap;
import org.mozilla.interfaces.nsIDOMNode;
import org.mozilla.interfaces.nsIDOMNodeList;

public class DumpDomAdapter extends SelectionAdapter {
	private final nsIDOMNodeList list;
	private final PrintStream out;

	public DumpDomAdapter(nsIDOMNodeList list, PrintStream out) {
		super();
		this.list = list;
		this.out = out;
	}

	public void widgetSelected(SelectionEvent e) {
		printNodeList(list);
	}

	public void printNodeList(final nsIDOMNodeList list) {
		for (int i = 0; i < list.getLength(); i++) {
			final nsIDOMNode item = list.item(i);
			printNode(item);
			final nsIDOMNamedNodeMap attributes = item.getAttributes();
			if (attributes != null) {
				for (int j = 0; j < attributes.getLength(); j++) {
					out.println("attributes");
					final nsIDOMNode attrItem = attributes.item(j);
					printNode(attrItem);
					printNodeList(attrItem.getChildNodes());
				}
			}
			printNodeList(item.getChildNodes());
		}
	}

	public void printNode(final nsIDOMNode node) {
		if (node.getNodeName() != null)
			out.print("\nname: " + node.getNodeName());
		out.print("\ttype: " + node.getNodeType());
		if (node.getNodeValue() != null)
			out.print("\tvalue: " + node.getNodeValue());
		if (node.getNamespaceURI() != null)
			out.print("\tURI: " + node.getNamespaceURI());
		if (node.getPrefix() != null)
			out.print("\tPrefix: " + node.getPrefix());
		if (node.getLocalName() != null)
			out.print("\tlocal name: " + node.getLocalName());
	}

}